package com.xykj.initial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xykj.initial.common.Constants;
import com.xykj.initial.entity.Account;
import com.xykj.initial.entity.User;
import com.xykj.initial.exception.ServiceException;
import com.xykj.initial.mapper.UserMapper;
import com.xykj.initial.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Account login(Account account) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, account.getUsername());
        queryWrapper.eq(User::getPassword, account.getPassword());
        User queryUser = userMapper.selectOne(queryWrapper);
        if (queryUser == null) {
            throw new ServiceException(Constants.CODE_605, "用户名或密码错误");
        }

        String role = "ROLE_USER";
        BeanUtils.copyProperties(queryUser, account);
        account.setRole(role);
        account.setPassword(null);
        return account;
    }

    @Override
    public void register(Account account) {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, account.getUsername());
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ServiceException(Constants.CODE_605, "用户名已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(account, user);
        userMapper.insert(user);
    }
}
